from fastapi import APIRouter,Depends
from app.utils.custom_route import CustomRoute
from app.utils.auth import get_current_user

from app.schema.auth import AuthDataSchema, LoginInputSchema, UserInfoSchema, AiInfoSchema
from app.schema.base import RespBaseSchema,RespDataSchema
from ..service.user import UserService

router = APIRouter(route_class=CustomRoute)


@router.post('/login')
async def login(*, login_input: LoginInputSchema):
    try:
        res = await UserService().login_by_code(login_input.code)
        return res
    except BaseException as e:
        print(e, 'login failed')
        return RespBaseSchema(code=50001,message='登陆失败')
      
@router.post('/refresh', response_model=AuthDataSchema, response_model_exclude_unset=True)
async def refresh(*, auth_data: dict = Depends(get_current_user)):
    try:
        return  (await UserService().refresh_token(auth_data))
    except BaseException as e:
        return RespBaseSchema(code=50001,message='刷新失败')

@router.get('/me',response_model=RespDataSchema)
async def read(auth_data: dict = Depends(get_current_user)):
    try:
        data= UserService(auth_data).read_me(auth_data)
        return RespDataSchema(data=data)
    except BaseException as e:
        print(e,'read me failed')
        return RespBaseSchema(code=401,message='查询失败')

@router.post('/update', response_model=RespBaseSchema)
async def update(*, info: UserInfoSchema, auth_data: dict = Depends(get_current_user)):
    try:
        info.id=auth_data.id
        user_service = UserService(auth_data)
        if info.avatar is not None:
            await user_service.update_ai_page(info)
        return user_service.update(info)
    except BaseException as e:
        return RespBaseSchema(code=50001,message='修改失败')

@router.post('/groupinfo')
async def get_group_info(ai: AiInfoSchema ,auth_data: dict = Depends(get_current_user)):
    try:
        user_info = await UserService(auth_data).get_group_info(ai.ai_id)
        if isinstance(user_info, str):
            return RespBaseSchema(code=50001,message=user_info)
        else:    
            return RespDataSchema(data=user_info)
    except BaseException as e:
        return RespBaseSchema(code=50001,message='查询失败')
